package com.gitee.ly.ymorm.transaction.jdbc;

import com.gitee.ly.ymorm.YmOrmConfig;
import com.gitee.ly.ymorm.log.YmOrmLog;
import com.gitee.ly.ymorm.log.YmOrmLogFactory;
import com.gitee.ly.ymorm.transaction.Transaction;
import com.gitee.ly.ymorm.transaction.TransactionIsolationLevel;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * JdbcTransaction
 *
 * @author ly
 **/
public class JdbcTransaction implements Transaction {

    private YmOrmLog log = YmOrmLogFactory.getLog(this.getClass());
    protected String uuid;
    protected YmOrmConfig ymOrmConfig;
    protected Connection connection;
    protected DataSource dataSource;
    protected TransactionIsolationLevel level;
    protected boolean autoCommit;

    public JdbcTransaction(String uuid, YmOrmConfig ymOrmConfig, DataSource dataSource, TransactionIsolationLevel level, boolean autoCommit) {
        this.uuid = uuid;
        this.ymOrmConfig = ymOrmConfig;
        this.dataSource = dataSource;
        this.level = level;
        this.autoCommit = autoCommit;
    }

    public JdbcTransaction(String uuid, YmOrmConfig ymOrmConfig, Connection connection) {
        this.uuid = uuid;
        this.ymOrmConfig = ymOrmConfig;
        this.connection = connection;
    }

    @Override
    public Connection getConnection() throws SQLException {
        if (connection == null) {
            openConnection();
        }
        return connection;
    }

    private void openConnection() throws SQLException {
        log.info("openConnection[Transaction-uuid" + uuid + "]");
        connection = dataSource.getConnection();
        if (level != null) {
            connection.setTransactionIsolation(level.getLevel());
        }
        if (connection.getAutoCommit() != autoCommit) {
            connection.setAutoCommit(autoCommit);
        }
    }

    @Override
    public void commit() throws SQLException {
        if (connection != null && !connection.getAutoCommit()) {
            log.info("commit[Transaction-uuid" + uuid + "]");
            connection.commit();
        }
    }

    @Override
    public void rollback() throws SQLException {
        if (connection != null && !connection.getAutoCommit()) {
            log.info("rollback[Transaction-uuid" + uuid + "]");
            connection.rollback();
        }
    }

    @Override
    public void close() throws SQLException {
        if (connection != null) {
            if (!connection.getAutoCommit()) {
                connection.setAutoCommit(true);
            }
            log.info("close[Transaction-uuid" + uuid + "]");
            connection.close();
        }
    }

    @Override
    public Integer getTimeout() {
        return null;
    }
}
